<?php defined('SYSPATH') or die('No direct script access.');
/**
 * @file rest.php
 * @brief 修改Rest类
 * @author Lionel Tsai
 * @version 1.0
 * @date 2012-02-17
 */

abstract class Controller_REST extends Kohana_Controller_REST {
	/** 重定义映射*/
	protected  $_action_map = array(
			'GET'    => 'get',
			'POST'   => 'post',
			'PUT'    => 'put',
			'DELETE' => 'delete',
			);
	/** 验证开关*/
	protected $_ifauth = TRUE;
	protected $_request_params = array();

	public function before()
	{
		$this->_request_params = array(
			'method' => $this->request->method()
			, 'controller' => $this->request->controller()
			, 'action' => $this->request->action()
			, 'directory' => $this->request->directory()
		);

		$raw = file_get_contents("php://input");
		parent::before();
		if($this->request->action() !== 'invalid' && $this->_action_requested !== 'index' )
		{
			$action = $this->_action_requested . '_' . $this->request->action();
			$this->request->action($action);
		}

		/** 验证token*/
		elseif($this->_ifauth and !$this->authorized())
		{
			$this->request->action = 'index';
		}

		/** 一般用户权限*/	
		$_POST = json_decode($raw, true);
	}

	public function action_index()
	{
	}

	public function authorized()
	{
		//如果系统忽略，返回true
			
		//
		$auth = Auth::instance();
		if(!$auth->use_sid()) {
			/**
			 * @brief 无sid，若提供appkey，看app是否需要登录
			 *			若需登录，返回未登录
			 *			否则，检查登录权限
			 */
			do {
				if(!isset($_GET['appkey']))
					break;

				/** 若需要登录，判断登录权限*/
				$app = ORM::factory('app', array('app_key' => $_GET['appkey']));
				if((BOOL)$app->needlogin)
					break;
				
				/** 应用是否有权限*/
				if($app->authorized($this->_request_params))
					return true;
				else {
					$this->response->body('app_or_api_not_allowed')->status(406);
					return false;
				}
			}while(0);

			$this->response->body('no_login')->status(401);
			return false;
		}
	}
}
